package periodTask

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Uuid"
	"sync"
)

type periodTaskManager struct {
	mutex         sync.RWMutex
	shareTaskList map[string]*periodTask
	onceTaskList  []IPeriodTask
}

func (e *periodTaskManager) queryShareTask(currentTime int64) map[string]IPeriodTask {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	result := make(map[string]IPeriodTask)
	for key, value := range e.shareTaskList {
		if currentTime > value.task.SchedulePeriod()*1000+value.time {
			result[key] = value.task
		}
	}

	// 返回一个浅拷贝副本
	return result
}

func (e *periodTaskManager) queryOnceTask() []IPeriodTask {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	result := e.onceTaskList

	e.onceTaskList = make([]IPeriodTask, 0)
	return result
}

func (e *periodTaskManager) insertTask(task IPeriodTask) {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	value := &periodTask{}
	value.task = task
	value.id = Uuid.RandomUUID()

	if value.task.TaskType() == TaskShare {
		e.shareTaskList[value.id] = value
	}
	if value.task.TaskType() == TaskOnce {
		e.onceTaskList = append(e.onceTaskList, value.task)
	}
}

func (e *periodTaskManager) updateShareTask(id string, time int64) {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	value, ok := e.shareTaskList[id]
	if !ok {
		return
	}

	if value.task.TaskType() != TaskShare {
		return
	}

	value.time = time
}
